<template>
    <div style="margin-left: auto;">
        <p>采购订单</p>
    </div>
    <div style="right: auto;">
        <span>
            <el-button type="primary" @click="SalesOrderAdd()">保存</el-button>
        </span>

    </div>
    <hr>
    <el-scrollbar style="height: 320px;color: dimgray">
        <div class="scrollbar-flex-content">
            <p class="scrollbar-demo-item">
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="单据编码：" style="width: 308px">
                        <el-input v-model="form.receiptNum" placeholder="" />
                    </el-form-item>
                    <el-form-item label="单据日期：" style="width: 308px">
                        <el-date-picker v-model="form.receiptDate" type="date" />
                    </el-form-item>
                    <el-form-item label="单据状态：" style="width: 308px">
                        <el-input v-model="form.receiptState" disabled />
                    </el-form-item>
                    <el-form-item label="业务状态：" style="width: 308px">
                        <el-select v-model="form.serviceStatus">
                            <el-option label="正常" value="正常" />
                            <el-option label="挂起" value="挂起" />
                            <el-option label="手工关闭" value="手工关闭" />
                            <el-option label="系统关闭" value="系统关闭" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="业务类型：" style="width: 308px">
                        <el-select v-model="form.businessType">
                            <el-option label="零部件" value="零部件" />
                            <el-option label="原材料" value="原材料" />
                            <el-option label="五金" value="五金" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="单据类型：" style="width: 308px">
                        <el-select v-model="form.auditor" disabled>
                            <el-option label="采购订单" value="采购订单" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="销售部门：" style="width: 308px">
                        <el-select v-model="form.department">
                            <el-option label="总经办" value="1" />
                            <el-option label="市场部" value="2" />
                            <el-option label="采购部" value="3" />
                            <el-option label="销售部" value="4" />
                            <el-option label="生产运营中心" value="5" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="销售人员：" style="width: 308px">
                        <el-select v-model="form.buyer">
                            <el-option label="赵多和" value="赵多和" />
                            <el-option label="姜楠" value="姜楠" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="操作员：" style="width: 308px">
                        <el-input v-model="form.operator" disabled />
                    </el-form-item>
                    <el-form-item label="审核员：" style="width: 308px">
                        <el-input disabled />
                    </el-form-item>
                    <el-form-item label="审核日期：" style="width: 308px">
                        <el-input type="date" disabled />
                    </el-form-item>
                    <el-form-item label="用料需求：" style="width: 308px">
                        <el-select v-model="form.materialDemand" disabled>
                            <el-option label="订单用料" value="订单用料" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="供方：">
                        <el-input v-model="form.system" style="width: 200px;float: left;" />
                        <el-link type="primary" @click="form1.dialogTableVisible = true"
                            style="width: 50px;float: left;">选择</el-link>
                    </el-form-item>
                    <div>
                        <el-dialog v-model="form1.dialogTableVisible" title="选择" width="980">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item label="供应商名称">
                                    <el-input v-model="formInline.supplierName" />
                                </el-form-item>
                                <el-form-item label="业务联系人">
                                    <el-input v-model="formInline.businessContact" />
                                </el-form-item>
                                <el-button type="primary" @click="SearchCustomerProfilelist">搜索</el-button>
                            </el-form>
                            <el-table :data="suppliers" stripe>
                                <el-table-column prop="supplierId" label="序号" />
                                <el-table-column prop="supplierName" label="供应商名称" />
                                <el-table-column prop="supplierAbbreviation" label="简称" />
                                <el-table-column prop="companyAddress" label="公司地址" />
                                <el-table-column prop="phone" label="电话" />
                                <el-table-column prop="businessContact" label="业务联系人" />
                                <el-table-column prop="materialTypeName" label="供应料品" />
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button type="primary"
                                            @click="SelectName(scope.row.supplierName)">选择</el-button>
                                    </template>
                                </el-table-column>

                            </el-table>

                            <div>
                                <tr>
                                    <td>
                                        <el-pagination v-model:current-page="formInline.pageIndex"
                                            v-model:page-size="formInline.pageSize" :page-sizes="[10, 20, 30, 40, 50]"
                                            :background="true" layout="total, slot, prev, pager, next"
                                            :total="formInline.totalCount" @size-change="handleSizeChange"
                                            @current-change="handleCurrentChange">
                                        </el-pagination>
                                    </td>
                                    <td>
                                        <el-pagination v-model:current-page="formInline.pageIndex"
                                            v-model:page-size="formInline.pageSize" :page-sizes="[10, 20, 30, 40, 50]"
                                            :background="true" layout="slot, sizes, jumper"
                                            :total="formInline.totalCount" @size-change="handleSizeChange"
                                            @current-change="handleCurrentChange">
                                        </el-pagination>
                                    </td>
                                </tr>
                            </div>
                        </el-dialog>
                    </div>
                    <el-form-item label="到货日期：" style="width: 308px">
                        <el-input v-model="form.deliveryDate" type="date" />
                    </el-form-item>
                    <el-form-item label="采购合同：" style="width: 308px">
                        <el-input v-model="form.purchasingContract" />
                    </el-form-item>
                    <el-form-item label="备注信息：" style="width: 308px">
                        <el-input v-model="form.remark" type="textarea" />
                    </el-form-item>
                </el-form>

            </p>
        </div>
    </el-scrollbar>

    <el-button type="primary" @click="add">新增物料</el-button>
    <!-- <el-button type="primary" @click="addlist">保存</el-button> -->
    <table style="border-collapse:collapse">
        <tr>
            <td>序号</td>
            <td>物料编码</td>
            <td>物料名称</td>
            <td>型号规格</td>
            <td>主计量</td>
            <td>需求日期</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>到货数量</td>
            <td>采购说明</td>
            <td>操作</td>
        </tr>
        <tr v-for="(ruleForm, index) in loge.healthArray">
            <td>
                {{ ruleForm.salesOrderMaterialId }}
            </td>
            <td>
                {{ ruleForm.materialCode }}
                <el-link type="primary" @click="xuanze(index)">选择</el-link>
                <div>
                    <el-dialog v-model="form1.dialogTableVisible111" title="选择物料" width="900" style="height: 600px;">
                        <div class="common-layout" style="width: 165px;float: left">
                            <el-container>
                                <el-aside width="165px" style="margin-left: 10px;">
                                    <el-tree ref="treeRef" class="filter-tree" :data="data" :props="defaultProps" style="
                width: 165px;
                border: 0px solid #ccc;
                float: left;
                height: 500px
                " default-expand-all :expand-on-click-node="false" :filter-node-method="filterNode"
                                        @node-click="handleNodeClick" />

                                </el-aside>
                                <el-main>
                                </el-main>
                            </el-container>
                        </div>
                        <div class="common-layout" style="float: right;top: 12px;">
                            <el-form :inline="true" :model="page" class="demo-form-inline">
                                <el-form-item label="物料编码">
                                    <el-input v-model="Materials.itemBianma" />
                                </el-form-item>
                                <el-form-item label="物料名称">
                                    <el-input v-model="Materials.itemName" />
                                </el-form-item>
                                <el-button type="primary" @click="SearchMaterialsShow">搜索</el-button>
                            </el-form>
                            <el-table :data="MaterialsShowlist" style="height: 500px;">
                                <el-table-column property="itemBianma" label="物料编码" width="150" />
                                <el-table-column property="itemName" label="物料名称" width="200" />
                                <el-table-column property="modelspecification" label="型号规格" />
                                <el-table-column property="measureId" label="主计量" />
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button type="primary"
                                            @click="Selectnumber(scope.row.itemBianma, scope.row.itemName, scope.row.modelspecification, index1)">选择</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>

                    </el-dialog>
                </div>
            </td>
            <td>
                {{ ruleForm.materialName }}
            </td>
            <td>
                {{ ruleForm.typeSpecification }}
                <br>
                <el-select v-model="ruleForm.color" placeholder="请选择" style="width: 100px">
                    <el-option lable="白色" value="白色"></el-option>
                    <el-option lable="黑色" value="黑色"></el-option>
                    <el-option lable="红色" value="红色"></el-option>
                    <el-option lable="黄色" value="黄色"></el-option>
                    <el-option lable="蓝色" value="蓝色"></el-option>
                </el-select>
            </td>
            <td>
                <el-select v-model="ruleForm.documentType" placeholder="请选择" style="width: 100px">
                    <el-option lable="台" value="台"></el-option>
                    <el-option lable="件" value="件"></el-option>
                    <el-option lable="个" value="个"></el-option>
                    <el-option lable="盒" value="盒"></el-option>
                </el-select>
            </td>
            <td>
                <el-input v-model="form.requirementDate" type="date" placeholder="请输入" style="width: 125px">
                </el-input>
            </td>
            <td>
                <el-input v-model="ruleForm.quantity" @blur="jisuan(index)" style="width: 100px">
                </el-input>
            </td>
            <td>
                <el-input v-model="ruleForm.unitPrice" @blur="jisuan(index)" style="width: 100px">

                </el-input>

            </td>
            <td>
                <el-input v-model="ruleForm.amount" style="width: 100px">

                </el-input>
            </td>
            <td>
                <el-input v-model="ruleForm.arrivalQuantity" style="width: 100px">
                </el-input>
            </td>
            <td>
                <el-input v-model="ruleForm.purchaseDescription" style="width: 100px">
                </el-input>
            </td>
            <td>
                <el-link style="color: red;" @click="del">删除</el-link>
            </td>
        </tr>
    </table>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import Cookie from 'cookies-ts'
import axios from 'axios'
import { number } from 'echarts'
const apiurls = import.meta.env.VITE_APP_API_URL_BasicInformationCommon;//5176
const bpiurls = import.meta.env.VITE_APP_API_URL_BasicInformationWrite;//5013
const cpiurls = import.meta.env.VITE_APP_API_URL_RBACCommon;//5214
const dpiurls = import.meta.env.VITE_APP_API_URL_RBACWrite;//5268
const epiurls = import.meta.env.VITE_APP_API_URL_SalesManagementCommon;//5227
const fpiurls = import.meta.env.VITE_APP_API_URL_SalesManagementWrite;//5020
const form1 = reactive({
    dialogTableVisible: false,
    dialogTableVisible111: false,
})
onMounted(() => {
    SearchCustomerProfilelist()
    SearchMaterialsShow()
    GetSuppliers()
    loadData()
    //绑定树形
    GetBang()
})
//映射用户名到操作员文本框里
const loadData = () => {
    if (cookie.get('employeeName') != null) {
        form.operator = cookie.get('employeeName') as string
    }
}
//选择客户表 反填客户名称
const SelectName = (supplierName: any) => {
    localStorage.setItem('supplierName', supplierName)
    if (localStorage.getItem('supplierName') != null) {
        form.system = localStorage.getItem('supplierName') as string
    }
    form1.dialogTableVisible = false
}
const formInline = reactive({
    supplierName: '',
    businessContact: '',
    materialTypeName: '',
    pageIndex: 1,
    pageSize: 10,
    pageCount: 0,
    totalCount: 0,

})

//供应商列表
const suppliers: any = ref([]);
const GetSuppliers = () => {
    axios
        .get(
            apiurls + '/api/Suppliers/SuppliersList',
            {
                params: {
                    supplierName: formInline.supplierName,
                    businessContact: formInline.businessContact,
                    materialTypeName: formInline.materialTypeName || 0,
                    pageIndex: formInline.pageIndex,
                    pageSize: formInline.pageSize,
                }
            }
        )
        .then((res) => {
            console.log(res.data.data);
            suppliers.value = res.data.data;
            formInline.pageCount = res.data.pageCount;
            formInline.totalCount = res.data.totalCount;
        })
        .catch((err) => {
            console.log(err);
        });
};
const index1 = ref(0)
const xuanze = (index: any) => {
    form1.dialogTableVisible111 = true
    index1.value = index
}
const cookie = new Cookie()
const router = useRouter()
const route = useRoute()
var price = 0;
var num = 0;
var amount = 0;
const jisuan = (index: number) => {
    price = loge.healthArray[index].quantity
    num = loge.healthArray[index].unitPrice
    amount = loge.healthArray[index].amount = price * num

}
const form = reactive({
    "receiptNum": "",
    "receiptState": "开立",
    "receiptDate": null,
    "businessType": "零部件",
    "serviceStatus": "正常",
    "department": "1",
    "buyer": "",
    "operator": '',
    "auditor": '采购订单',
    "approvalDate": null,
    "materialDemand": "订单用料",
    "system": "",
    "deliveryDate": "",
    "purchasingContract": "",
    "remark": "",
    "orderNumber": "",
    "materialCode": localStorage.getItem('materialCode') as string,
    "materialName": localStorage.getItem('itemName') as string,
    "typeSpecification": "",
    "color": "",
    "documentType": "",
    "requirementDate": null,
    "quantity": num,
    "unitPrice": price,
    "amount": amount,
    "arrivalQuantity": 0,
    "purchaseDescription": localStorage.getItem('itemBianma') as string,
})



const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.label.includes(value);
};

const Selectnumber = (materialCode: any, materialName: any, typeSpecification: any, index: any) => {
    console.log(index)
    localStorage.setItem('materialCode', materialCode)
    localStorage.setItem('itemName', materialName)
    localStorage.setItem('modelspecification', typeSpecification)
    // cookie.set('materialCode', materialCode)
    // cookie.set('itemName', materialName)
    // cookie.set('modelspecification', typeSpecification)
    if (localStorage.getItem('materialCode') != null || localStorage.getItem('itemName') != null || localStorage.getItem('modelspecification') != null || localStorage.getItem('measureId') != null) {
        loge.healthArray[index].materialCode = localStorage.getItem('materialCode') as string
        loge.healthArray[index].materialName = localStorage.getItem('itemName') as string
        loge.healthArray[index].typeSpecification = localStorage.getItem('modelspecification') as string
    }
    console.log(loge.healthArray[index])
    form1.dialogTableVisible111 = false
}
//树形级联
const defaultProps = {
    children: 'children',
    label: 'label',
}
//树形数据
var data = ref([])
function GetBang() {
    axios({
        url: apiurls + '/api/Materials/GetmaterialTree',
        method: 'get'
    })
        .then((res) => {
            data.value = res.data.data
        })
}
const handleNodeClick = (data: any) => {

    uptform.materialTypeName = data.label
    uptform.pId = data.value
    console.log(uptform.pId)
}
const uptform = reactive({
    materialTypeName: '',
    pId: 0,
});


//新增行序号
const numbers = ref(1)
const loge = reactive({
    healthArray: <any>[
        reactive({
            salesOrderMaterialId: numbers.value,
            orderNumber: "",
            materialCode: "",
            materialName: '',
            typeSpecification: "",
            color: "",
            documentType: '',
            requirementDate: '',
            quantity: 0,
            unitPrice: 0,
            amount: 0,
            arrivalQuantity: 0,
            purchaseDescription: "",
        })
    ]
});
const aaa = cookie.get('employeeName')
console.log(aaa)
//新增行
const add = () => {
    loge.healthArray.push(reactive({
        materialCode: "",
        materialName: '',
        typeSpecification: "",
        color: "",
        documentType: '',
        requirementDate: '',
        quantity: 0,
        unitPrice: 0,
        amount: 0,
        arrivalQuantity: 0,
        purchaseDescription: "",
    }))
}
//删除行
const del = () => {
    loge.healthArray.splice(loge.healthArray.length - 1, 1)
    ElMessage.warning({
        message: '删除成功',
    })
}
const Materials = reactive({
    itemBianma: "",
    itemName: ""
})
const MaterialsShowlist = ref([])
const SearchMaterialsShow = () => {
    axios.get(apiurls + '/api/Materials/MaterialesSearch', {
        params: {
            materialTypeId: uptform.pId,
            materialCode: Materials.itemBianma,
            itemName: Materials.itemName
        }
    }).then((res) => {
        MaterialsShowlist.value = res.data.data2
        console.log(MaterialsShowlist.value);
    })
}
const page = reactive({
    customerName: "",
    businessContacts: "",
    PageIndex: 1,
    PageSize: 100,
    totalCount: 0,
    pageCount: 0,
})
const handleSizeChange = (val: number) => {
    page.PageSize = val;
    SearchCustomerProfilelist();
}
const handleCurrentChange = (val: number) => {
    page.PageIndex = val;
    SearchCustomerProfilelist();
}
const CustomerProfilelist = ref([])
const SearchCustomerProfilelist = () => {
    axios.post(epiurls + '/api/SalesOrder/SearchCustomerProfile', {
        customerName: page.customerName,
        businessContacts: page.businessContacts,
        PageIndex: page.PageIndex,
        PageSize: page.PageSize
    }).then((res) => {
        CustomerProfilelist.value = res.data.data
        page.totalCount = res.data.totalCount
        page.pageCount = res.data.pageCount;
    })
}


//采购订单添加
const SalesOrderAdd = () => {
    console.log(loge.healthArray);
    if (form.receiptNum == "") {
        ElMessage.error("请输入")
        return;
    }


    axios.post(bpiurls + '/api/Supplier/PurchaseOrderCreate', form)
        .then((res) => {
            if (res.data.code == 0) {
                ElMessage({
                    message: '新增成功',
                    type: 'success',
                })
                router.push('/PurchasingManagement/PurchaseOrde')
            } else {
                ElMessage({
                    message: '新增失败',
                    type: 'error',
                })
            }
        })
        .catch((err) => {
            console.log(err)
        })
}
//销售订单物料添加
// const addlist = () => {
//     const request: any = ref({});
//     request.SalesOrderMaterials = loge.healthArray;
//     console.log(request)
//     axios.post('http://localhost:5020/api/SalesManagementWrite/CreateSalesOrderMaterial', request)
//         .then((res) => {
//             if (res.data.code == 0) {
//                 ElMessage({
//                     message: '新增成功',
//                     type: 'success',
//                 })
//                 // router.push('/SalesOrder')
//             } else {
//                 ElMessage({
//                     message: '新增失败',
//                     type: 'error',
//                 })
//             }
//         })
//         .catch((err) => {
//             console.log(err)
//         })
// }
</script>

<style scoped>
.scrollbar-flex-content {
    display: flex;
}

.scrollbar-demo-item {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 1800px;
    height: 300px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
}
</style>
<style scoped>
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
    border-top: 1px solid #ccc;
    /* 设置顶部边框为3px宽度的红色 */
    padding: 10px;
    text-align: center;
}

/* 设置 td 的样式 */

table td {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: center;
    font-size: 14px;
    height: 60px;
    width: 150px;
    white-space: nowrap;
    /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
    max-width: 100%;
    overflow-x: auto;
    /* 启用水平滚动 */
    margin: 20px 0;
    /* 设置容器的外边距 */
}

/* :deep(.el-input__wrapper) {
    box-shadow: none;
    text-align: center;
}

:deep(.el-select__wrapper) {
    box-shadow: none;
}

::v-deep(.center-input .el-input__inner) {
    text-align: center;
} */
</style>